package com.example.administrator.readbook.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.example.administrator.readbook.R;
import com.example.administrator.readbook.bean.SearchBookBean;
import com.example.administrator.readbook.greendao.BookDao;
import com.example.administrator.readbook.greendao.GreenDaoBookBean;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/7/3.
 */

public class AdapterSearchBook extends BaseAdapter {
    private Context context;
    private List<SearchBookBean.BooksBean> searchBookList = new ArrayList<>();

    public AdapterSearchBook(Context context, List<SearchBookBean.BooksBean> searchBookList) {
        this.context = context;
        this.searchBookList = searchBookList;
    }

    @Override
    public int getCount() {
        return searchBookList.size();
    }

    @Override
    public Object getItem(int position) {
        return searchBookList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final SearchBookBean.BooksBean booksBean = searchBookList.get(position);
        ViewHolder viewHolder = null;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.adapter_searchbook, null);
            viewHolder = new ViewHolder();
            viewHolder.titleTv = convertView.findViewById(R.id.adapter_search_title);
            viewHolder.authorTv = convertView.findViewById(R.id.adapter_search_author);
            viewHolder.newChapterTv = convertView.findViewById(R.id.adapter_search_newchapter);
            viewHolder.contentTV = convertView.findViewById(R.id.adapter_search_content);
            viewHolder.addTv = convertView.findViewById(R.id.adapter_search_add);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        viewHolder.titleTv.setText(booksBean.getTitle());
        viewHolder.authorTv.setText(booksBean.getAuthor());
        viewHolder.newChapterTv.setText(booksBean.getLastChapter());
        viewHolder.contentTV.setText(booksBean.getShortIntro());
        viewHolder.addTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BookDao.insertBook(new GreenDaoBookBean(booksBean.get_id(), booksBean.get_id(), booksBean.getTitle(), booksBean.getLastChapter(), booksBean.getCover()));
            }
        });
        return convertView;
    }

    class ViewHolder {
        TextView titleTv, authorTv, newChapterTv, contentTV, addTv;
    }
}
